package main

// 本地构建了docker镜像aktools，监听18080端口，提供股票数据API
// docker run -d -p 18080:8080 registry.cn-shanghai.aliyuncs.com/akfamily/aktools:1.8.95

// @title aktools API
// @version 1.0
// @description 用于股票数据查询的API服务
// @host localhost:8088
// @BasePath /api
import (
	"easy-stock-analyzer/aktools/utility"
	"os"

	"encoding/json"

	"github.com/gin-gonic/gin"

	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"

	_ "easy-stock-analyzer/aktools/docs"
)


func main() {
	r := gin.Default()

	// Swagger文档UI
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, ginSwagger.URL("/swagger.json")))
	
	// Swagger JSON文档
	r.GET("/swagger.json", func(c *gin.Context) {
		c.File("./docs/swagger.json")
	})

	// 动态注册API端点
	for key, cfg := range utility.AkToolsCfg {
		r.GET("/api/"+key, func(c *gin.Context) {
			queryParams := c.Request.URL.Query()
			datas, resp := utility.FetchData(cfg.Url, utility.ChangeParams(queryParams, cfg.Params))
			data, err := utility.ChangeBody(datas, cfg.Bodys, cfg.BodyType)
			if err != nil {
				c.JSON(resp.Code, gin.H{
					"code":    resp.Code,
					"message": resp.Message,
					"data":    err.Error(),
				})
				return
			}

			if data == nil {
				c.JSON(resp.Code, gin.H{
					"code":    resp.Code,
					"message": resp.Message,
				})
				return
			}

			c.JSON(resp.Code, json.RawMessage(data))
		})
	}

	// 启动服务
	port := os.Getenv("SERVER_PORT")
	if port == "" {
		port = "8088"
	}
	r.Run(":" + port)
}
